package com.code.soulqlexpress.func;

import com.ql.util.express.ArraySwap;
import com.ql.util.express.InstructionSetContext;
import com.ql.util.express.OperateData;
import com.ql.util.express.instruction.op.OperatorBase;

/**
 * @author yzh
 * @date 2020/6/8
 * @content switch(条件表达式 ， 结果 ， 条件表达式 ， 结果 ， .... ， 默认值)
 */
public class SwitchOperator extends OperatorBase {

    @Override
    public OperateData executeInner(InstructionSetContext parent, ArraySwap list) throws Exception {
        int length = list.length;
        for (int i = 0; i < list.length; i = i + 2) {
            OperateData operateData = list.get(i);
            Object switchCase = operateData.getObject(parent);
            Boolean result = null;
            if (switchCase instanceof Boolean) {
                result = (Boolean) switchCase;
            } else {
                continue;
            }
            if (result) {
                OperateData operateNumData = list.get(i + 1);
                Object operateNum = operateNumData.getObject(parent);
                return new OperateData(operateNum, Integer.class);
            }
        }
        //奇数，配置默认值，返回最后一个值
        if (!isEvenNumber(length)) {
            return new OperateData(list.get(length - 1), Integer.class);
        }
        return null;
        //偶数，未配置默认值，返回-1
//        return new OperateData(-1, Integer.class);
    }

    private static boolean isEvenNumber(int length) {
        return length % 2 == 0;
    }
}
